import { inBrowser } from '@vc/utils';
import { type Ref, unref } from 'vue';
import { useEventListener } from './useEventListener';

export type UseClickAwayOptions = {
  eventName?: string;
  listenerOptions?: boolean | AddEventListenerOptions;
};

/**
 * @description 监听点击元素外部的事件。
 * @author wfd
 * @date 2022/11/14 20:16
 * @example  useClickAway(root, () => {
 *             console.log('click outside!');
 *           });
 * @param {Element | Ref<Element | undefined> | Array<Element | Ref<Element | undefined>>} target
 * @param {EventListener} listener
 * @param {UseClickAwayOptions} options
 */
export function useClickAway (target: Element | Ref<Element | undefined> | Array<Element | Ref<Element | undefined>>,
  listener: EventListener, options: UseClickAwayOptions = {}) {
  if (!inBrowser) {
    return;
  }
  
  const { eventName = 'click', listenerOptions } = options;
  
  const onClick = (event: Event) => {
    const targets = Array.isArray(target) ? target : [target];
    const isClickAway = targets.every((item) => {
      const element = unref(item);
      
      return element && !element.contains(event.target as Node);
    });
    
    if (isClickAway) {
      listener(event);
    }
  };
  
  useEventListener(document.body, eventName, onClick, listenerOptions);
}
